<template>
  <h2>吾圈洗群工具</h2>
  <el-row :gutter="20">
    <el-col :span="8">
      <div class="grid-content ep-bg-purple" />
    </el-col>
    <el-col :span="8">
      <div class="grid-content ep-bg-purple" />
      <el-form label-width="auto" label-position="Right" size="large" v-if="!showcz">
        <el-form-item label="手机号">
          <el-input v-model="userName" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="password" type="password" />
        </el-form-item>
        <el-form-item label="服务器id">
          <el-input v-model="serverId" />
        </el-form-item>
        <el-form-item label="卡密">
          <el-input v-model="kakaka" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit" style="width: 100%;">登录</el-button>
        </el-form-item>
      </el-form>
    </el-col>
    <el-col :span="8">
      <div class="grid-content ep-bg-purple" />
    </el-col>
  </el-row>
  <el-tabs tab-position="left" style="max-height: 800px" class="demo-tabs" type="border-card" v-if="showcz">
    <el-tab-pane label="基础设置">
      <el-row ::gutter="20">
        <el-col :span="8">
          <el-card>
            <el-table :data="groupList" ref="singleTableRef1"
              @selection-change="handleSelectionChange" max-height="700">
              <el-table-column type="selection" :selectable="selectable"  />
              <el-table-column property="groupID" label="群ID"  />
              <el-table-column property="name" label="群名称" />
            </el-table>
          </el-card>
        </el-col>
        <el-col :span="16">
          <el-card>
            <!-- 设置 -->
             <el-row>
                <el-col :span="8"> <el-button type="success"  @click="getGroupren" :disabled="disabled">获取群员</el-button></el-col>
                <el-col :span="8"> <el-input v-model="yanzhengmsg" placeholder="请输入添加好友验证消息" /></el-col>
                <el-col :span="8"><el-button type="primary" @click="addGroupren" :disabled="disabled2">添加群员</el-button></el-col>
             </el-row>

             <el-table :data="getGrouprenList" ref="singleTableRef" 
                @selection-change="handleSelectionChange2"  max-height="700" v-loading="loading" element-loading-text="正在获取中，请稍候">
                <el-table-column type="selection" :selectable="selectable2"  />
                <el-table-column property="nick" label="群员名称" />
                <el-table-column property="userID" label="群员id" />
                <el-table-column property="groupID" label="群id" />
                <el-table-column property="status" label="添加状态" />
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </el-tab-pane>
    <el-tab-pane label="本账号好友">
      <el-row>
                <el-col :span="6"><el-button type="success" @click="getF">更新好友列表</el-button></el-col>
                <el-col :span="6"><el-button type="success" @click="daochuF">导出好友列表</el-button></el-col>
                <el-col :span="6"><el-button type="success" @click="dialogTableVisible = true" :disabled="disabled3">发送文本消息</el-button></el-col>
                <el-col :span="6"><el-button type="success" @click="dialogTableVisible2 = true" :disabled="disabled3">发送图片消息</el-button></el-col>
             </el-row>
      <el-table :data="Friends" ref="singleTableRef2" id="singleTableRef"
                @selection-change="handleSelectionChange3"  max-height="700" v-loading="loading2" element-loading-text="正在发送中，请稍候">
                <el-table-column type="selection" :selectable="selectable3" />
                <el-table-column property="profile.nick" label="好友名称" />
                <el-table-column property="userID" label="好友id" />
                <el-table-column property="appid" label="好友appid" />
                <el-table-column property="status" label="状态" />
            </el-table>


            <el-dialog v-model="dialogTableVisible" title="发送文本消息" width="500">
                  <el-input
                    v-model="textarea"
                    :autosize="{ minRows: 10, maxRows: 20 }"
                    type="textarea"
                    placeholder="请输入"
                  />
                  <p></p>
                  <el-button type="success" @click="sendmsg" :disabled="disabled4">发送消息</el-button>
            </el-dialog>
            <el-dialog v-model="dialogTableVisible2" title="发送图片消息" width="500">
              <input ref="inputRef" @change="handleImageSelected" type="file" id="imageInput" name="image" accept="image/*" />
              <el-button type="success" @click="sendimgmsg" :disabled="disabled5">发送消息</el-button>
            </el-dialog>
    </el-tab-pane>

    <el-tab-pane label="手动添加好友">
      <el-row>
        <el-col :span="8"><input type="file" @change="handleFileUpload" placeholder="导入账号"/></el-col>
        <el-col :span="8"><el-button type="success" @click="addFuser" :disabled="disabled6">添加进本账号</el-button></el-col>
      </el-row>
      <el-table :data="drFriends" ref="singleTableRef5"
                @selection-change="handleSelectionChange5"  max-height="700"  element-loading-text="正在导入,请稍等">
        <el-table-column type="selection" :selectable="selectable5" />
        <el-table-column property="nick" label="好友名称" />
        <el-table-column property="userID" label="好友id" />
        <el-table-column property="appid" label="好友appid" />
        <el-table-column property="status" label="状态" />
      </el-table>
    </el-tab-pane>
    <el-tab-pane label="监控群设置" name="first" style="width: 100%;">
      <el-row :gutter="20">
        <el-col :span="12"><div class="grid-content ep-bg-purple" />
          <el-card >
            <template #header>
              <div class="card-header">
                <span>需要监控的群(实时)</span>
              </div>
            </template>
            <el-table :data="groupList" @selection-change="handqun" style="width: 100%;" max-height="700">
              <el-table-column type="selection"  width="55" />
              <el-table-column property="groupID" label="群ID" width="120" />
              <el-table-column property="name" label="群名称" />
            </el-table>
          </el-card>
        </el-col>
        <el-col :span="12"><div class="grid-content ep-bg-purple" />
          <el-card >
            <template #header>
              <div class="card-header">
                <span>需要过滤的用户</span>
              </div>
            </template>
            <el-button type="primary" @click="addfile">保存</el-button>
            <p>每个用户名请用|隔开</p>
            <el-input v-model="heimingdan" clearable type="textarea" :rows="10"  />
          </el-card>
        </el-col>
      </el-row>
    </el-tab-pane>

    <el-tab-pane label="实时流水详细" name="second" style="width: 100%;">
      <el-table :data="xiazhu1" style="width: 100%;" max-height="700">
        <el-table-column property="nick" label="用户名"/>
        <el-table-column property="xiazhu" label="下注详情" />
        <el-table-column property="xzls" label="下注流水" />
        <el-table-column property="date2" label="下注时间" />
      </el-table>
    </el-tab-pane>

    <el-tab-pane label="往期流水详细" name="third" style="width: 100%;">
      <el-date-picker
          v-model="value1"
          type="date"
          placeholder="选择日期"
          size="large"
          format="YYYY/MM/DD"
          value-format="YYYY/MM/DD"
      />
      <el-button type="primary" @click="getlslistday"  >查询单天</el-button>
      <el-button type="primary" @click="getlslist">查询全部</el-button>
      <el-button type="primary" @click="dctj">导出全部用户下注</el-button>
      <p></p>
      <el-row :gutter="20">
        <el-col :span="24"><div class="grid-content ep-bg-purple-dark" />
          <el-table :data="filterTableData" border  id="tableRef3" ref="tableRef3" style="width: 100%;" max-height="700">
            <el-table-column property="nick" label="用户名"/>
            <el-table-column property="userid" label="用户ID"/>
            <el-table-column property="zj" label="下注总流水"/>
            <el-table-column property="xznum" label="下注数" />
            <el-table-column property="jz" label="均值" />
            <el-table-column  align="center">
              <template #header>
                <el-input v-model="search" size="large" placeholder="输入userID" />
              </template>
              <template #default="scope">
                <el-button size="small" type="primary" @click="handleEdit(scope.$index, scope.row)">查回记录</el-button>
                <p></p>
                <el-button size="small" type="success" @click="xiazhujl(scope.$index, scope.row)">下注详情</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-table :data="lsxiazhu" style="width: 100%;" :border="true" id="tableRef" ref="tableRef" v-show="false">
            <el-table-column property="nick" label="用户名"/>
            <el-table-column property="userid" label="用户id"/>
            <el-table-column property="xiazhu" label="下注详情" />
            <el-table-column property="xzls" label="下注流水" />
            <el-table-column property="date2" label="下注时间" />
          </el-table>
        </el-col>
      </el-row>
      <el-dialog v-model="dialogTableVisible10" title="用户查回记录" >
        <el-table :data="userch" style="width: 100%;">
          <el-table-column property="nick" label="用户名"/>
          <el-table-column property="type" label="查回"  />
          <el-table-column property="number" label="金额" />
          <el-table-column property="date2" label="时间" />
        </el-table>
      </el-dialog>

      <el-dialog v-model="dialogTableVisible12" title="用户下注记录" >
        <el-button type="primary" @click="dcxz">导出下注</el-button>
        <p></p>
        <el-table :data="userxiazhu" style="width: 100%;" :border="true" id="tableRef2" ref="tableRef2">
          <el-table-column property="nick" label="用户名"/>
          <el-table-column property="userid" label="用户id"/>
          <el-table-column property="xiazhu" label="下注详情" />
          <el-table-column property="xzls" label="下注流水" />
          <el-table-column property="date2" label="下注时间" />
        </el-table>
      </el-dialog>
    </el-tab-pane>
  </el-tabs>
</template>
<script>
import axios from 'axios'
import { ElMessage } from 'element-plus'
import TencentCloudChat from '@tencentcloud/chat'
import TIMUploadPlugin from 'tim-upload-plugin'
import CryptoJS from 'crypto-js'
import {  nextTick  } from 'vue'
import * as XLSX from 'xlsx'
import moment from 'moment'
import FileSaver from "file-saver"
import { openDB } from 'idb';
export default {
  name: 'App',
  data() {
    return {
      sizeForm: [],
      userName: '',
      serverId: '',
      password: '',
      xiazhutuo:'',
      kakaka:'',
      accid: '',
      token:'',
      accessToken:'',
      chat:null,
      groupList:[],
      xuanGroupList:[],
      showcz:false,
      yanzhengmsg:'',
      getGrouprenList:[],
      xuanzhongGrouprenlist:[],
      disabled:true,
      disabled2:true,
      value1:'',
      disabled3:true,
      disabled6:true,
      loading:false,
      loading2:false,
      Friends:[],
      Crypto: CryptoJS.enc.Utf8.parse("666888\0\0\0\0\0\0\0\0\0\0"),
      xuanFriends:[],
      dialogTableVisible:false,
      dialogTableVisible2:false,
      textarea:'',
      disabled4:false,
      disabled5:true,
      file:null,
      drFriends:[],
      drxuan:[],
      userxiazhu:[],
      zhangdan:[],
      userch:[],
      xzuser:[],
      idb:null,
      dbName :'my-database',
      lsxiazhu:[],
      lsch:[],
      xiazhu1:[],
      heimingdan:'',
      lsxiazhuid:0,
      lschid:0,
      jiankongqun:[],
      chuser:[],
      search:'',
      dialogTableVisible12:false,
      dialogTableVisible10:false,
    }
  },
  components: {
    
  },
  updated(){

  },
  computed:{
    filterTableData(){
      return this.xzuser.filter(
          (data) =>
              !this.search ||
              data.userid.toLowerCase().includes(this.search.toLowerCase())
      )
    }
  },
  created(){
    this.idb = openDB(this.dbName,2,{
      upgrade(db) {
        db.createObjectStore('user');
        db.createObjectStore('userch');
        db.createObjectStore('userxiazhu');
      },
    })
    this.getItems('userxiazhu').then(res=>{
      if(res.length!=0){
        this.lsxiazhu = res
        this.lsxiazhuid = res.length+1
      }else{
        this.lsxiazhu=[]
        this.lsxiazhuid = 1
      }
    })
    this.getItems('userch').then(res=>{
      if(res.length!=0){
        this.lsch = res
        this.lschid = res.length+1
      }else{
        this.lsch=[]
        this.lschid = 1
      }
    })
    this.getItems('user').then(res=>{
      if(res.length!=0){
        this.heimingdan = res[0].data
      }else{
        this.heimingdan = '国际_机器人|'
      }
    })
  },
  watch: {
    drxuan(newV){
      if(newV.length!=0){
        this.disabled6 = false
      }else{
        this.disabled6 =true
      }
    },
    textarea(newV){
      if(newV !=''){
        this.disabled4 = false
      }else{
        this.disabled4 =true
      }
    },
    xuanGroupList(newV){
      if(newV.length!=0){
        this.disabled = false
      }else{
        this.disabled =true
      }
    },
    xuanzhongGrouprenlist(newV){
      if(newV.length!=0){
        this.disabled2 = false
      }else{
        this.disabled2 =true
      }
    },
    xuanFriends(newV){
      if(newV.length!=0){
        this.disabled3 = false
      }else{
        this.disabled3 =true
      }
    }
  },
  mounted() {
  },
  methods: {
    dctj(){
      nextTick(()=> {
        // 获取表格的DOM
        let filename = '全部用户下注.xlsx'
        const xlsxParam = { raw: true } //转化成Excel使用原始格式
        const elTable = XLSX.utils.table_to_book(document.getElementById('tableRef'), xlsxParam)
        const wbout = XLSX.write(elTable, { bookType: 'xlsx', bookSST: true, type: 'array' })
        try {
          FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), filename)
        } catch (e) {
          if (typeof console !== 'undefined') {
            console.log(e, wbout)
          }
        }
      })
    },
    dcxz(){
      nextTick(()=> {
        // 获取表格的DOM
        let filename = 'xiazhu.xlsx'
        const xlsxParam = { raw: true } //转化成Excel使用原始格式
        const elTable = XLSX.utils.table_to_book(document.getElementById('tableRef2'), xlsxParam)
        const wbout = XLSX.write(elTable, { bookType: 'xlsx', bookSST: true, type: 'array' })
        try {
          FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), filename)
        } catch (e) {
          if (typeof console !== 'undefined') {
            console.log(e, wbout)
          }
        }
      })
    },
    handleEdit(index,row){
      console.log(index)
      this.userch = this.lsch.filter(item=>item.userid===row.userid)
      if(this.userch.length==0){
        ElMessage.error('没有记录')
      }else{
        this.dialogTableVisible10 = true
      }
    },
    xiazhujl(index,row){
      console.log(index)
      this.userxiazhu = this.lsxiazhu.filter(item=>item.userid === row.userid)
      if(this.userxiazhu.length==0){
        ElMessage.error('没有记录')
      }else{
        this.dialogTableVisible12 = true
      }
    },
    getlslist(){
      this.getItems('userxiazhu').then(res=>{
        if(res.length!=0){
          this.lsxiazhu = res
          this.lsxiazhuid = res.length+1
          let xy =this.lsxiazhu
          let user = []
          xy.forEach(list=>{
            user.push({
              userid:list.userid,
              nick:list.nick
            })
          })
          let userarr = Array.from(new Set(user.map(JSON.stringify)), JSON.parse)
          userarr.forEach(item=>{
            let userxz = xy.filter(list=>list.userid == item.userid)
            let sum = userxz.reduce((total, obj) => total + obj.xzls, 0)
            let jz = parseInt(sum)/parseInt(userxz.length)
            this.xzuser.push(
                {
                  userid:item.userid,
                  nick:item.nick,
                  zj:sum,
                  xznum:userxz.length,
                  jz:parseFloat(jz.toFixed(2))
                }
            )
          })
          console.log(this.xzuser)
        }else{
          this.lsxiazhu=[]
          this.lsxiazhuid = 1
        }
      })
      this.getItems('userch').then(res=>{
        if(res.length!=0){
          this.lsch = res
          this.lschid = res.length+1
        }else{
          this.lsch=[]
          this.lschid = 1
        }
      })
    },
    getlslistday(){
      this.getItems('userxiazhu').then(res=>{
        if(res.length!=0){
          this.lsxiazhu = res
          this.lsxiazhuid = res.length+1
        }else{
          this.lsxiazhu=[]
          this.lsxiazhuid = 1
        }
      })
      this.getItems('userch').then(res=>{
        if(res.length!=0){
          this.lsch = res
          this.lschid = res.length+1
        }else{
          this.lsch=[]
          this.lschid = 1
        }
      })
      this.xzuser = []
      this.chuser=[]
      let xy =this.lsxiazhu=this.lsxiazhu.filter(item=>item.issue != undefined && moment(item.date2).format('YYYY/MM/DD') == this.value1)
      this.chuser =this.lsch= this.lsch.filter(item=>item.type != undefined && moment(item.date1).format('YYYY/MM/DD') == this.value1)
      let user = []
      xy.forEach(list=>{
        user.push({
          userid:list.userid,
          nick:list.nick
        })
      })
      let userarr = Array.from(new Set(user.map(JSON.stringify)), JSON.parse)
      userarr.forEach(item=>{
        let userxz = xy.filter(list=>list.userid == item.userid)
        let sum = userxz.reduce((total, obj) => total + obj.xzls, 0)
        let jz = parseInt(sum)/parseInt(userxz.length)
        this.xzuser.push(
            {
              userid:item.userid,
              nick:item.nick,
              zj:sum,
              xznum:userxz.length,
              jz:parseFloat(jz.toFixed(2))
            }
        )
      })
    },
    async addItem(dataname,item,id) {
      let create_at = moment().format('YYYY-MM-DD HH:mm:ss')
      let update_at = moment().format('YYYY-MM-DD HH:mm:ss')
      item.create_at = create_at
      item.update_at = update_at
      const db = await this.idb;
      const tx = db.transaction(dataname, 'readwrite');
      const store = tx.objectStore(dataname);
      store.add(item,id);
    },
    // 查询记录
    async  getItems(dataname) {
      const db = await this.idb;
      const tx = db.transaction(dataname, 'readonly');
      const store = tx.objectStore(dataname);
      return store.getAll();
    },
    // 删除记录
    async  deleteItem(dataname,id) {
      const db = await this.idb;
      const tx = db.transaction(dataname, 'readwrite');
      const store = tx.objectStore(dataname);
      store.delete(id);
    },
    // 更新记录
    async  updateItem(dataname,updates, id) {
      let update_at = moment().format('YYYY-MM-DD HH:mm:ss')
      updates.update_at = update_at
      const db = await this.idb;
      const tx = db.transaction(dataname, 'readwrite');
      const store = tx.objectStore(dataname);
      store.put({...updates}, id);
    },
    // 清空存储
    async  clearStore(dataname) {
      const db = await this.idb;
      const tx = db.transaction(dataname, 'readwrite');
      const store = tx.objectStore(dataname);
      store.clear();
    },
    handleFileUpload(event){
      this.drFriends=[]
      const file = event.target.files[0];
      const reader = new FileReader();
      reader.onload = (e) => {
        const data = new Uint8Array(e.target.result);
        const workbook = XLSX.read(data, { type: 'array' });
        const firstSheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[firstSheetName];
        const jsonData = XLSX.utils.sheet_to_json(worksheet);
        jsonData.forEach(list=>{
          let dd = this.Friends.filter(item=>item.userID == list['好友id'])
          if(dd.length==0){
            this.drFriends.push(
                {
                  'nick':list['好友名称'],
                  'userID':list['好友id'],
                  'appid':list['好友appid']
                }
            )
          }
        })
      }
      reader.readAsArrayBuffer(file)
    },
    textPa(bastr){
      let srcs = bastr;
      let decrypt = CryptoJS.AES.decrypt(srcs, this.Crypto, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
      });
      return decrypt.toString(CryptoJS.enc.Utf8)
    },
    addfile(){
      this.updateItem('user',{id:1,data:this.heimingdan},1)
      ElMessage({
        message: '保存成功',
        type: 'success',
      })
      this.getItems('user').then(res=>{
        if(res[0].data){
          this.heimingdan = res[0].data
        }else{
          this.heimingdan = ''
        }
      })
    },
    daochuF(){
      // 导出xlsx
      nextTick(()=> {
        // 获取表格的DOM
        let filename = 'data.xlsx'
        const xlsxParam = { raw: true } //转化成Excel使用原始格式
        const elTable = XLSX.utils.table_to_book(document.getElementById('singleTableRef'), xlsxParam)
        const wbout = XLSX.write(elTable, { bookType: 'xlsx', bookSST: true, type: 'array' })
        try {
          FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), filename)
        } catch (e) {
          if (typeof console !== 'undefined') {
            console.log(e, wbout)
          }
        }
      })
    },
    getF(){
      this.Friends=[]
      let promise = this.chat.getFriendList();
      promise.then((imResponse)=> {
        ElMessage({
          message: '获取好友列表成功',
          type: 'success',
        })
        this.Friends = imResponse.data; // 好友列表
        this.Friends.forEach(list=>{
          axios.post('https://api.ts28.com.cn/wqAppid',{token:this.accessToken,accid:list.userID}).then((res)=>{
           list.appid = res.data.data.appid
          })
        })
      }).catch(()=> {
        ElMessage({
          message: '获取好友列表失败，请重试',
          type: 'error',
        })
      });
    },
    handleImageSelected(event){
      console.log(event)
      this.file = event.target.files[0];
      this.disabled5 = false
      if (!this.file) {
        this.disabled5 = true
      }
    },
    sendimgmsg(){
      this.dialogTableVisible2 = false
      this.loading2 = true
      let ttd = 0
      this.xuanFriends.forEach(list=>{
        let message = this.chat.createImageMessage({
          to: list.userID,
          conversationType: TencentCloudChat.TYPES.CONV_C2C,
          payload: {
            file: document.getElementById('imageInput'),
          },
        });
        // 2. 发送消息
        let promise = this.chat.sendMessage(message);
        promise.then(()=> {
          // 发送成功
          list.status = '发送成功'
          ttd++;
        }).catch(() =>{
          // 发送失败
          list.status = '发送失败'
        });
      })
      let tt  = setInterval(()=>{
        if(ttd != 0){
          ElMessage({
            message:'发送成功，一共发送：'+ttd+'名用户',
            type: 'success',
          })
          this.loading2=false
          clearInterval(tt)
        }
      },300)
    },
    sendmsg(){
      this.dialogTableVisible = false
      this.loading2 = true
      let ttd = 0
      this.xuanFriends.forEach(list=>{
        let message = this.chat.createTextMessage({
          to: list.userID,
          conversationType: TencentCloudChat.TYPES.CONV_C2C,
          payload: {
            text: this.textarea
          },
        });
        // 2. 发送消息
        let promise = this.chat.sendMessage(message);
        promise.then(()=> {
          // 发送成功
          list.status = '发送成功'
          ttd++
        }).catch(() =>{
          // 发送失败
          list.status = '发送失败'
        });
      })
      let tt  = setInterval(()=>{
        if(ttd != 0){
          ElMessage({
            message:'发送成功，一共发送：'+ttd+'名用户',
            type: 'success',
          })
          this.loading2=false
          clearInterval(tt)
        }
      },300)
    },
    getGroupren(){
      // 获取群员
      this.getGrouprenList = []
      let yy = 0;
      this.loading = true
      this.disabled = true
      this.xuanGroupList.forEach(list => {
        let intnum = parseInt(parseInt(list.memberCount)/30)+1
        for (let index = 0; index < intnum; index++) {
          let promise = this.chat.getGroupMemberList({
            groupID: list.groupID,
            count: 30,
            offset:index*30,
            role:TencentCloudChat.TYPES.GRP_MBR_ROLE_MEMBER
          }); // 从0开始拉取30个群成员
          promise.then((imResponse)=> {
            console.log(imResponse.data.memberList); // 群成员列表
            for (let x = 0; x < imResponse.data.memberList.length; x++) {
              if(imResponse.data.memberList[x].userID != this.accid && this.Friends.filter(item=>item.userID === imResponse.data.memberList[x].userID).length == 0){
                let data = imResponse.data.memberList[x]
                data.groupID =  list.groupID
                this.getGrouprenList.push(data)
                yy++;
              }
            }
          }).catch((imError)=> {
            console.warn('getGroupMemberList error:', imError);
          });
        }
      });
      let tt  = setInterval(()=>{
        if(yy!=0){
          ElMessage({
            message:'获取成功，一共获取用户：'+yy+'',
            type: 'success',
          })
          this.loading=false
          this.disabled = false
          clearInterval(tt)
        }
      },300)
    },
    addGroupren(){
      // 添加群员
      this.xuanzhongGrouprenlist.forEach(list=>{
          axios.post('https://api.ts28.com.cn/addwq',{
            token:this.accessToken,
            appid:list.groupID,
            toAccount:list.userID,
            msg:this.yanzhengmsg
          }).then(res=>{
            list.status = res.data.msg
          }).catch(()=>{
            list.status = '链接超时，请重试'
          })
      })
    },
    addFuser(){
      this.drxuan.forEach(list=>{
        axios.post('https://api.ts28.com.cn/addwqtwo',{
          token:this.accessToken,
          appid:list.appid,
          toAccount:list.userID,
          msg:this.yanzhengmsg
        }).then(res=>{
          list.status = res.data.msg
        }).catch(()=>{
          list.status = '链接超时，请重试'
        })
      })
    },
    onSubmit() {
      // 登录
      axios.get('https://xq.ts28.com.cn/getka?kaka='+this.kakaka).then(res=>{
        if(res.data.code == 200){
          // 存在卡密
          // 处理是否到期
          let creDate = moment(res.data.data.create_at).add(30,'day').format('YYYY-MM-DD HH:mm:ss')
          let thisDate = moment()
          console.log(thisDate.diff(creDate,'days'))
          if(!thisDate.diff(creDate,'days')>=0){
            let data = {
              password: this.password,
              serverId: this.serverId,
              userName: this.userName
            }
            let login = axios.create({
              baseURL: 'https://api.ts28.com.cn/',
              timeout: 5000, // 请求超时时间
            })
            login.post('/wqxqlogin', data).then(res => {
              if (res.data.code == 200) {
                //登录成功
                ElMessage({
                  message: res.data.msg,
                  type: 'success',
                })
                this.accid = res.data.data.accid
                this.toekn = res.data.data.token
                this.imappid = parseInt(res.data.data.imAppid)
                this.accessToken =  res.data.data.access_token
                // 登录腾讯im
                let options = {
                  SDKAppID: parseInt(res.data.data.imAppid)
                }
                this.chat = TencentCloudChat.create(options);
                this.chat.registerPlugin({'tim-upload-plugin': TIMUploadPlugin})
                let promise = this.chat.login({ userID: res.data.data.accid, userSig: res.data.data.token });
                promise.then((imResponse) => {
                  ElMessage({
                    message: '连接服务器成功',
                    type: 'success',
                  })
                  moment.locale('zh-cn')
                  setTimeout(() => {
                    this.chat.on(TencentCloudChat.EVENT.MESSAGE_RECEIVED, this.getInfo)
                    this.chat.getGroupList().then(imResponses => {
                      this.groupList = imResponses.data.groupList
                      this.showcz = true
                    }).catch(imError => {
                      console.warn('getGroupList error:', imError); // 获取群组列表失败的相关信息
                    })
                    this.getF()
                  }, 1000)
                  if (imResponse.data.repeatLogin === true) {
                    // 标识账号已登录，本次登录操作为重复登录。
                    console.log(imResponse.data.errorInfo);
                    ElMessage({
                      message: '重复登录，请退出其他页面登录后再试',
                      type: 'error',
                    })
                  }
                }).catch((imError) => {
                  console.log(imError)
                  ElMessage({
                    message: '连接服务器失败请重试',
                    type: 'error',
                  })
                });
              } else {
                //登录失败
                ElMessage({
                  message: res.data.msg,
                  type: 'error',
                })
              }
            }).catch(err => {
              console.log(err)
            })
          }else{
            ElMessage({
                message:'卡密过期',
                type: 'error',
              })
          }
 
        }else{
          ElMessage({
                message: res.data.msg,
                type: 'error',
              })
        }
      })

    },
    getNumbers(str) {
      const regex = /\d+/g;
      return str.match(regex).map(Number);
    },
    // 接收消息
    getInfo(event){
      const messageList = event.data;
      messageList.forEach((message) => {
        if (message.type === TencentCloudChat.TYPES.MSG_TEXT && this.jiankongqun.some(obj=>obj.groupID=== message.to)) {
          let msg = this.textPa(message.payload.text)
          let date1 = moment().format('YYYY/MM/DD')
          let date2 = moment().format('YYYY/MM/DD HH:mm:ss')
          // 处理开奖
          if(msg.includes('期：')){
            // 开奖了
            let number = this.getNumbers(msg)
            let issue = number[0] // 期号
            console.log(issue)
            this.xiazhu1.forEach(list=> {
              this.addItem('userxiazhu', {
                    nick: list.nick,
                    userid: list.userid,
                    date2: list.date2,
                    xzls:list.xzls,
                    xiazhu:list.xiazhu,
                    id: this.lsxiazhuid,
                    issue:issue
                  },this.lsxiazhuid
              )
              this.lsxiazhuid++
            })
            this.xiazhu1 = []
          }else if(msg.indexOf('回') == 0){
            // 回分
            console.log('回')
            let jine = this.getNumbers(msg)[0]
            this.addItem('userch',{nick:message.nick,
              userid:message.from,
              type:'回分',
              number:jine,
              date1:date1,
              date2:date2,
              id:this.lschid,
            },this.lschid
            )
            this.lschid++

          }else if(msg.indexOf('查') == 0){
            // // 查分
            console.log('查')
            let jine = this.getNumbers(msg)[0]
            this.addItem('userch',{nick:message.nick,
                  userid:message.from,
                  type:'查分',
                  number:jine,
                  date1:date1,
                  date2:date2,
                  id:this.lschid,
                },this.lschid
            )
            this.lschid++
          }else if(msg.indexOf('取消') == 0){
            console.log('取消')
            this.xiazhu1 = this.xiazhu1.filter(obj=>obj.userid !== message.from)
          }else if(msg.indexOf('改') == 0){
            console.log('改')
            this.xiazhu1 = this.xiazhu1.filter(obj=>obj.userid !== message.from)
            let newmsg = msg.replaceAll("改", "");
            let data = this.TextD(newmsg)
            if(data !== 0){
              // 是下注，添加
              this.xiazhu1.push({
                date1:date1,
                date2:date2,
                nick:message.nick,
                userid:message.from,
                xiazhu:data.xiazhu,
                xzls:data.xzls
              })
            }
          } else {
            if(this.heimingdan.indexOf(message.nick) == -1){
              let data = this.TextD(msg)
              console.log(data)
              if(data !== 0){
                // 是下注，添加
                this.xiazhu1.push({
                  date1:date1,
                  date2:date2,
                  nick:message.nick,
                  userid:message.from,
                  xiazhu:data.xiazhu,
                  xzls:data.xzls
                })
              }
            }
          }
        }
      });
    },
    removeEmptyItems(arr) {
      const regex = /^\s*$/; // 匹配空串或只有空白字符的正则表达式
      return arr.filter(item => !regex.test(item));
    },
    TextD(str){
      let parts = str.split(/(\d+)/);
      let reparts = this.removeEmptyItems(parts);
      var xiazhuls = 0;
      for(let i =0;i<reparts.length;i++){
        if(reparts[0]=='大'||reparts[0]=='小'||reparts[0]=='单'||reparts[0]=='双'||reparts[0]=='大单'||reparts[0]=='大双'||reparts[0]=='小单'||reparts[0]=='小双'||reparts[0]=='极大'||reparts[0]=='极小'||reparts[0]=='对子'||reparts[0]=='豹子'||reparts[0]=='顺子'||reparts[0]=='顺'){
          // 数字在后面
          if(!isNaN(parseInt(reparts[i+1]))){
            // 是下注金额
            if(reparts[i].trim()=='大' || reparts[i].trim()=='小'  || reparts[i].trim()=='单'  || reparts[i].trim()=='双'  || reparts[i].trim()=='大单'  || reparts[i].trim()=='大双'  || reparts[i].trim()=='小双'  || reparts[i].trim()=='小单'  || reparts[i].trim()=='极大'|| reparts[i].trim()=='极小' || reparts[i].trim()=='豹子'|| reparts[i].trim()=='对子'|| reparts[i].trim()=='顺子'){
              xiazhuls+=parseInt(reparts[i+1])
            }
          }
        }else if(!isNaN(parseInt(reparts[i]))){
          if(reparts[i+1].trim()=='大' || reparts[i+1].trim()=='小'  || reparts[i+1].trim()=='单'  || reparts[i+1].trim()=='双'  || reparts[i+1].trim()=='大单'  || reparts[i+1].trim()=='大双'  || reparts[i+1].trim()=='小双'  || reparts[i+1].trim()=='小单'  || reparts[i+1].trim()=='极大'|| reparts[i+1].trim()=='极小' || reparts[i+1].trim()=='豹子'|| reparts[i+1].trim()=='对子'|| reparts[i+1].trim()=='顺子'){
            xiazhuls+=parseInt(reparts[i])
          }else{
            break;
          }
        }
      }
      // 处理点数字
      let numArr = []
      for(let i =0;i<reparts.length;i++){
        if(reparts[i]=='.' || reparts[i]=='艹'|| reparts[i]=='操'|| reparts[i]=='草'|| reparts[i]=='点'){
          numArr.push(i)
        }
      }
      for(let i = 0;i<numArr.length;i++){
        let numindex = parseInt(numArr[i])
        let num = parseInt(reparts[numindex+1])
        if(!isNaN(num)){
          xiazhuls+=parseInt(num)
        }
      }
      if(xiazhuls != 0){
        return {
          xiazhu:str,
          xzls:xiazhuls
        }
      }else{
        return 0
      }
    },
    handleSelectionChange(list) {
      this.xuanGroupList = list
    },
    handleSelectionChange2(list){
      this.xuanzhongGrouprenlist = list
    },
    handleSelectionChange3(list){
      this.xuanFriends = list
    },
    handleSelectionChange5(list){
      this.drxuan = list
    },
    handqun(list){
      this.jiankongqun = list
    }
  },
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  width: 70%;
  margin: 0 auto;
}

.demo-tabs .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
.el-table{
  display: flex;
  flex-direction: column;
}
.el-table__body-wrapper {
  order: 1;
}
</style>

